package com.distribute.application.manage;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.flag;
import com.distribute.framework.core.web.helper.Utils;

@Aspect
@Order(2)
@Configuration(value="manage.applicationInterceptor")
public class ApplicationInterceptor{
	
	@Around("execution(public com.distribute.framework.core.lang.Protocol com.distribute.application.manage..*Controller.*(..))")
    public Object afterInvoke(ProceedingJoinPoint joinPoint) throws Throwable {
    	Utils.getServletResponse().setHeader("Access-Control-Allow-Origin", "*");//跨域设置
		Utils.getServletResponse().addHeader("JSESSIONID", Utils.getServletRequest().getSession().getId());
		if(LoginHelper.getLogin()==null && Utils.getServletRequest().getServletPath().endsWith(".do")){
        	return Protocol.create(false, "对不起，请先登录...", "login_error");
        }
		Object controller = joinPoint.getTarget();
		flag classFlag = controller.getClass().getAnnotation(flag.class);
		MethodSignature ms = (MethodSignature)joinPoint.getSignature();
		flag methodFlag = ms.getMethod().getAnnotation(flag.class);
		Protocol returnValue = (Protocol) joinPoint.proceed();
		if(returnValue!=null){
			returnValue.set("basePath", Utils.getRequest("basePath"));
			if(methodFlag!=null){
				Method getItemsMethod = controller.getClass().getMethod("getItems");
				if(getItemsMethod!=null){
					getItemsMethod.setAccessible(true);
					Map items = (Map) getItemsMethod.invoke(null);
					returnValue.getData().putAll(items);
				}
			}
		}
        return returnValue;
    }
}